package com.grgbanking.it.common.formatter;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.Parser;
import org.springframework.format.Printer;

import com.grgbanking.it.common.formatter.annotation.TimestampFormat;

/**
 * Timestamp注解格式化工厂
 * 
 * TimestampFormatAnnotationFormatterFactory
 * 
 * @author 潘广伟
 * @Email p_3er@qq.com
 * @Date 2015-1-28 上午10:20:47
 * 
 * @version 1.0.0
 *
 */
public class TimestampFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<TimestampFormat>{
	private final Set<Class<?>> fieldTypes;  
    private final TimestampFormatter formatter;  

	public TimestampFormatAnnotationFormatterFactory() {
		Set<Class<?>> set = new HashSet<Class<?>>();  
        set.add(Timestamp.class);  
        this.fieldTypes = set;  
        this.formatter = new TimestampFormatter();
	}

	@Override
	public Set<Class<?>> getFieldTypes() {
		return fieldTypes;
	}

	@Override
	public Parser<Timestamp> getParser(TimestampFormat annotation, Class<?> fieldType) {
		return formatter;  
	}

	@Override
	public Printer<Timestamp> getPrinter(TimestampFormat annotation, Class<?> fieldType) {
		return formatter;  
	}

	/**
	 * 字符转Timestamp类型格式化类
	 * 
	 * TimestampFormatter
	 * 
	 * @author 潘广伟
	 * @Email p_3er@qq.com
	 * @Date 2015-1-28 上午11:34:35
	 * 
	 * @version 1.0.0
	 *
	 */
	private class TimestampFormatter implements Formatter<Timestamp>,Serializable{
		private static final long serialVersionUID = -818656464607971661L;

		@Override
		public String print(Timestamp value, Locale locale) {
			if(value == null) {  
	            return "";  
	        }  
			return value.toString();
		}

		@Override
		public Timestamp parse(String value, Locale locale) throws ParseException {
			if(value.length() == 16){
				value = new StringBuffer(value).append(":00").toString();
			}
			return Timestamp.valueOf(value);
		}

	}

}
